import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { createStorage } from "@/utils/storage";
import { getSystemInfoSync } from "@tarojs/taro";
import i18n from "@/i18n";

// 获取系统语言
const getSystemLanguage = () => {
  try {
    const { language } = getSystemInfoSync();
    const normalizedLanguage = language.replace("_", "-");
    return normalizedLanguage;
  } catch (error) {
    console.error("获取系统语言失败:", error);
    return "zh-CN";
  }
};

interface LanguageState {
  currentLanguage: string;
  changeLanguage: (lang: string) => void;
}

export const useLanguageStore = create<LanguageState>()(
  persist(
    (set) => ({
      currentLanguage: getSystemLanguage(),
      changeLanguage: (lang: string) => {
        i18n.changeLanguage(lang);
        set({ currentLanguage: lang });
      },
    }),
    {
      name: "language",
      storage: createJSONStorage(() => createStorage() as any),
    }
  )
);
